import { HOST } from "./constant.js";

// 请求基础路径
const baseUrl = HOST;
const request = (options = {}) => {
  options.header = {
    "Content-Type": "application/json;charset=UTF-8",
  };
  if (options.login) {
    options.header.Authorization = uni.getStorageSync("token");
  }
  return new Promise((resolve, reject) => {
    if (options.loading) {
      uni.showLoading({
        title: options.loading_title,
        mask: true,
      });
    }
    uni.request({
      url: baseUrl + options.url || "",
      method: options.type || "GET",
      data: options.data || {},
      header: options.header || {},
      timeout: 8000,
      success(res) {
        if (res.data.code == 401) {
          //用户Token失效，需要重新登录
          uni.removeStorageSync("token");
          wx.showModal({
            showCancel: false,
            confirmText: "确定",
            content: res.data.message,
            success(res) {
              uni.reLaunch({
                url: "/pages/loading/loading",
              });
            },
          });
        } else {
          //请求成功
          resolve(res.data);
        }
      },
      fail(err) {
        uni.showToast({
          title: "请求失败，请检查网络",
          icon: "none",
        });
        reject(err);
      },
      complete() {
        if (options.loading) {
          uni.hideLoading();
        }
      },
    });
  });
};

const get = (url, data, options = {}) => {
  options.type = "GET";
  options.data = data;
  options.url = url;
  return request(options);
};

const post = (url, data, options = {}) => {
  options.type = "POST";
  options.data = data;
  options.url = url;
  return request(options);
};

export default {
  baseUrl,
  get,
  post,
};
